#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
#include <stdarg.h>
#include <sys/timerfd.h>

#include "librc.h"

int snprintfcat(char *dst, size_t size, const char *fmt, ...)
{
	va_list ap;
	size_t len = strnlen(dst, size);
	int ret;

	va_start(ap, fmt);
	ret = vsnprintf(dst + len, size - len, fmt, ap);
	va_end(ap);

	return len + ret;
}

int start_timer(int msec)
{
	int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
	if (tfd < 0)
		return -1;

	struct timespec ts;
	ts.tv_sec = msec / 1000;
	ts.tv_nsec = (msec % 1000) * 1000000;
	struct itimerspec new_timeout;
	struct itimerspec old_timeout;
	bzero(&new_timeout, sizeof(new_timeout));
	bzero(&old_timeout, sizeof(old_timeout));
	new_timeout.it_value = ts;
	new_timeout.it_interval.tv_sec =
	new_timeout.it_interval.tv_nsec = 0;

	if (timerfd_settime(tfd, 0, &new_timeout, &old_timeout) < 0)
		return -1;

	return tfd;
}

int check_timer(int tfd)
{
	uint64_t exp;

	if (tfd < 0)
		return 1;
	
	if (read(tfd, &exp, sizeof(uint64_t)) > 0)
		return 1;
	return 0;
}

int close_timer(int tfd)
{

	if (tfd < 0)
		return 1;

	close(tfd);
	return 0;
}
